import React, { useState } from 'react'
import { List, ActionSheet } from 'antd-mobile'
import { Image } from 'antd-mobile'

import type {
  Action,
} from 'antd-mobile/es/components/action-sheet'

const Profile = () => {

  const actions: Action[] = [
    { text: '相机', key: 'camera' },
    { text: '相册', key: 'picture' },
  ]

  const [visible, setVisible] = useState(false)
  const [myImage, setMyImage] = useState(null)

  // 拍照
  const takePic = () => {
    alert('拍照')
    // 拍照
    navigator.camera.getPicture(onSuccess, onError, {
      quality: 50,
      destinationType: 1
    })

    function onSuccess(imageURI) {
      setMyImage(imageURI)
    }

    function onError(message) {
      alert("拍照失败：" + message)
    }
  }

  // 从相册中选取
  const getPic = () => {
    alert('从相册中选取')
    console.log('myImage:', myImage);
    navigator.camera.getPicture(onSuccess, onError, {
      quality: 50,
      destinationType: 1,
      sourceType: 0
    })

    function onSuccess(imageURI) {
      setMyImage(imageURI)
    }

    function onError(message) {
      alert("拍照失败：" + message)
    }
  }

  return (
    <>
      <List header=''>
        <List.Item
          extra={
            <Image
              src={myImage == null ? require('../../assets/logo192.png') : myImage}
              style={{ borderRadius: 20 }}
              fit='cover'
              width={40}
              height={40}
            />
          }
          clickable
          arrow={false}
          onClick={() => setVisible(true)}
        >
          头像
        </List.Item>
        <List.Item extra='我是钢铁侠' arrow={false}>
          名字
        </List.Item>
      </List>
      <ActionSheet
        extra='请选择你要进行的操作'
        cancelText='取消'
        visible={visible}
        actions={actions}
        onAction={(action, index) => {
          console.log(action, index)
          if (index === 0) {
            takePic()
          } else if (index === 1) {
            getPic()
          }
          setVisible(false)
        }}
        onClose={() => setVisible(false)}
      />
    </>
  )
}

export default Profile